﻿var actionURL = "ashx/XQHHandler.ashx";
var uid;
var cid = "";
var xqhlist = "";
var dtOpstart = "";
var dtOpend = "";
var filterObj;
Array.prototype.deleteElementByValue = function (varElement) {
    var numDeleteIndex = -1;
    for (var i = 0; i < this.length; i++) {
        // 严格比较，即类型与数值必须同时相等。
        if (this[i] === varElement) {
            this.splice(i, 1);
            numDeleteIndex = i;
            break;
        }
    }
    return numDeleteIndex;
}
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
function ConvertJSONDateToJSDate(jsondate) {
    var date = new Date(parseInt(jsondate, 10));
    return date;
}
var mylayout = {
    init: function (size) {
        $('#layout').width(size.width - 4).height(size.height - 4).layout();
        var center = $('#layout').layout('panel', 'center');
        center.panel({
            onResize: function (w, h) {
                $('#histList').datagrid('resize', { width: w, height: h });
            }
        });
    },
    resize: function (size) {
        mylayout.init(size);
        $('#layout').layout('resize');
    }
};

$(function () {
    Highcharts.setOptions({
        lang: {
            contextButtonTitle: "图表导出菜单",
            decimalPoint: ".",
            downloadJPEG: "下载JPEG图片",
            downloadPDF: "下载PDF文件",
            downloadPNG: "下载PNG文件",
            downloadSVG: "下载SVG文件",
            drillUpText: "返回 {series.name}",
            loading: "加载中",
            months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            noData: "没有数据",
            numericSymbols: ["千", "兆", "G", "T", "P", "E"],
            printChart: "打印图表",
            resetZoom: "恢复缩放",
            resetZoomTitle: "恢复图表",
            shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            thousandsSep: ",",
            weekdays: ["星期一", "星期二", "星期三", "星期三", "星期四", "星期五", "星期六", "星期天"]
        }
    });
    var size = { width: $(window).width(), height: $(window).height() };
    $('#dtOpstart,#dtOpend').datebox({ width: 100 });
    mylayout.init(size);
    uid = getUrlParam("uid");
    DicCategory.bindTree();

    autoResize({ dataGrid: '#histList', gridType: 'datagrid', callback: grid.bind, height: 280,width: 200 });
    //WChartJS.init();
    $('#a_search').click(search);
    $('#avgbtn').click(phoneavg);
    $('#avgm').click(mavg);
    $('#a_export').click(function () {
        if (cid != "") {
            var ee = new ExportExcel('histList');
            ee.go(cid);
        }
        else {
            msg.error('对不起，请选择设备再导出！');
        }
    });

});
function changefx(d)
{   
    var res = "";
    if (d < 15 || d >= 345)
        res = "北";
    else if (d >= 15 && d < 45)
        res = "东北偏北";
    else if (d >= 45 && d < 75)
        res = "东北偏东";
    else if (d >= 75 && d < 105)
        res = "东";
    else if (d >= 105 && d < 135)
        res = "东南偏东";
    else if (d >= 135 && d < 165)
        res = "东南偏南";
    else if (d >= 165 && d < 195)
        res = "南";
    else if (d >= 195 && d < 225)
        res = "西南偏南";
    else if (d >= 225 && d < 255)
        res = "西南偏西";
    else if (d >= 255 && d < 285)
        res = "西";
    else if (d >= 285 && d < 315)
        res = "西北偏西";
    else if (d >= 315 && d < 345)
        res = "西北偏北";
    else res = d;
    return res;
}
var DicCategory = {
    bindTree: function () {
        $('#xqhNum').tree({
            url: '/status_xqh/ashx/XQHHandler.ashx?Action=xqhNums&uid=' + uid,
            onLoadSuccess: function (node, data) {
                if (data.length == 0) {
                    $('#noCategoryInfo').fadeIn();
                }
                $('body').data('categoryData', data);
            },
            onClick: function (node) {
                var cc = node.attributes.Phone;
                xqhlist = node.attributes.XQHlist;
                cid = cc;
                var ruleArr = [];
                dtOpstart = $('#dtOpstart').datebox('getValue');
                dtOpend = $('#dtOpend').datebox('getValue');
                if (dtOpstart != '')
                    ruleArr.push({ "field": "datetime", "op": "ge", "data": dtOpstart });
                if (dtOpend != '')
                    ruleArr.push({ "field": "datetime", "op": "le", "data": dtOpend });
                if (ruleArr.length > 0) {
                    filterObj = { groupOp: 'AND', rules: ruleArr };
                    $('body').data('where', JSON.stringify(filterObj));
                }
                if (xqhlist != "") {
                    var chs = xqhlist.split(',');
                    
                    var s = "[[";                   
                    $.each(chs, function () {
                        if (this != "风向")
                            s = s + "{field:'" + this + "',title:'" + this + "',width:80},";
                        else
                            s = s + "{field:'" + this + "',title:'" + this + "',width:80,formatter: function(value,row,index){ return changefx(value)}},";
                            
                         });
                    s = s + "{field:'datetime',title:'更新时间',width:160}";
                    s = s + "]]";
                    chs.deleteElementByValue("风向");
                    $('#histList').datagrid({
                        title: "设备[" + node.attributes.username + "] 的历史记录",
                        url: '/status_xqh/ashx/XQHHandler.ashx?Action=phone',
                        columns: eval(s),
                        queryParams: { devID: cc },
                        onLoadSuccess: function (data) {
                            WChartJS.init(chs);
                            var md;
                            var t1 = "";
                            $.each(data.rows, function (k, v) {
                                md = v["datetime"];
                                md = md.replace(/-/g, "/");
                                md = Date.parse(md);
                                t1 =  md + ","+t1;

                            });
                            t1 = t1 = "[" + t1 + "]";
                            wchartInstance.xAxis[0].setCategories(eval(t1));
                            for (var i = 0; i < chs.length; i++) {
                                t1 = "";
                                $.each(data.rows, function (k, v) {
                                    md = v["datetime"];
                                    t1 = "[" + v[chs[i]] + "],"+t1;

                                });
                                t1 = "[" + t1 + "]";
                                wchartInstance.series[i].setData(eval(t1));
                            }
                        }
                    });

                }
                else {
                    msg.error('对不起，设备没有设置气候参数！');
                }

            }
        });
    },
    reload: function () {
        $('#xqhNum').tree('reload');
    },
    getSelected: function () {
        return $('#xqhNum').tree('getSelected');
    }
};
function phoneavg()
{
    if (xqhlist != "") {
        var chs = xqhlist.split(',');
        dtOpstart = $('#dtOpstart').datebox('getValue');
        dtOpend = $('#dtOpend').datebox('getValue');
        var ruleArr = [];
        //if (cid != "") {
        //    ruleArr.push({ "field": "devID", "op": "eq", "data": cid });
        //}
        if (dtOpstart != '')
            ruleArr.push({ "field": "datetime", "op": "ge", "data": dtOpstart });
        if (dtOpend != '')
            ruleArr.push({ "field": "datetime", "op": "le", "data": dtOpend });
        if (ruleArr.length > 0) {
            filterObj = { groupOp: 'AND', rules: ruleArr };
            $('body').data('where', JSON.stringify(filterObj));
        }
        $('#histList').datagrid({
            //title: "设备[" + node.attributes.username + "] 的历史记录",
            url: '/status_xqh/ashx/XQHHandler.ashx?Action=phoneavg',
            //columns: eval(s),
            queryParams: { filter: JSON.stringify(filterObj), devID: cid },
            onLoadSuccess: function (data) {
                WChartJS.init(chs);
                var md;
                var t1 = "";
                $.each(data.rows, function (k, v) {
                    md = v["datetime"];
                    md = md.replace(/-/g, "/");
                    md = Date.parse(md);
                    t1 = md + ","+t1;

                });
                t1 = t1 = "[" + t1 + "]";
                wchartInstance.xAxis[0].setCategories(eval(t1));
                for (var i = 0; i < chs.length; i++) {
                    t1 = "";
                    $.each(data.rows, function (k, v) {
                        md = v["datetime"];
                        t1 = "[" + v[chs[i]] + "],"+t1;

                    });
                    t1 = "[" + t1 + "]";
                    wchartInstance.series[i].setData(eval(t1));
                }
            }
        });
    }
    else {
        msg.error('对不起，设备没有设置气候参数！');
    }

}

function mavg() {
    if (xqhlist != "") {
        var chs = xqhlist.split(',');
        dtOpstart = $('#dtOpstart').datebox('getValue');
        dtOpend = $('#dtOpend').datebox('getValue');
        var ruleArr = [];
        //if (cid != "") {
        //    ruleArr.push({ "field": "devID", "op": "eq", "data": cid });
        //}
        if (dtOpstart != '')
            ruleArr.push({ "field": "datetime", "op": "ge", "data": dtOpstart });
        if (dtOpend != '')
            ruleArr.push({ "field": "datetime", "op": "le", "data": dtOpend });
        if (ruleArr.length > 0) {
            filterObj = { groupOp: 'AND', rules: ruleArr };
            $('body').data('where', JSON.stringify(filterObj));
        }
        $('#histList').datagrid({
            //title: "设备[" + node.attributes.username + "] 的历史记录",
            url: '/status_xqh/ashx/XQHHandler.ashx?Action=mavg',
            //columns: eval(s),
            queryParams: { filter: JSON.stringify(filterObj), devID: cid },
            onLoadSuccess: function (data) {
                WChartJS.init(chs);
                var md;
                var t1 = "";
                $.each(data.rows, function (k, v) {
                    md = v["datetime"]+"-01";
                    md = md.replace(/-/g, "/");
                    md = Date.parse(md);
                    t1 = md + "," + t1;

                });
                t1 = t1 = "[" + t1 + "]";
                wchartInstance.xAxis[0].setCategories(eval(t1));
                for (var i = 0; i < chs.length; i++) {
                    t1 = "";
                    $.each(data.rows, function (k, v) {
                        md = v["datetime"];
                        t1 = "[" + v[chs[i]] + "]," + t1;

                    });
                    t1 = "[" + t1 + "]";
                    wchartInstance.series[i].setData(eval(t1));
                }
            }
        });
    }
    else {
        msg.error('对不起，设备没有设置气候参数！');
    }

}

var grid = {
    bind: function (winSize) {
        $('#histList').datagrid({
            toolbar: '#toolbar',
            title: "祥辰小气候历史数据列表",
            iconCls: 'icon icon-list',
            width: winSize.width,
            height: winSize.height,
            nowrap: true, //折行
            rownumbers: true, //行号
            striped: true, //隔行变色
            idField: 'ID', //主键
            singleSelect: true, //单选
            columns: [[                
                { title: '更新时间', field: 'datetime', width: 150, align: 'center' }
            ]],            
            pagination: true,
            pageSize: PAGESIZE            
        });
    },
    getSelectedRow: function () {
        return $('#histList').datagrid('getSelected');
    },
    reload: function () {
        $('#histList').datagrid('clearSelections').datagrid('reload', { filter: '' });
    }
};

function createParam(action, keyid) {
    var o = {};
    var query = top.$('#uiform').serializeArray();
    query = convertArray(query);
    o.jsonEntity = JSON.stringify(query);
    o.action = action;
    o.keyid = keyid;
    return "json=" + JSON.stringify(o);
}
function search() {
    dtOpstart = $('#dtOpstart').datebox('getValue');
    dtOpend = $('#dtOpend').datebox('getValue');
    var ruleArr = [];
    //if (cid != "") {
    //    ruleArr.push({ "field": "devID", "op": "eq", "data": cid });
    //}
    if (dtOpstart != '')
        ruleArr.push({ "field": "datetime", "op": "ge", "data": dtOpstart });
    if (dtOpend != '')
        ruleArr.push({ "field": "datetime", "op": "le", "data": dtOpend });
    if (ruleArr.length > 0) {
        filterObj = { groupOp: 'AND', rules: ruleArr };
        $('body').data('where', JSON.stringify(filterObj));
        $('#histList').datagrid('load', { filter: JSON.stringify(filterObj), devID: cid });
    } else {
        grid.reload();
    }

}
var wchartInstance;
var WChartJS = {
    init: function (chs) {
        var s = "[";
        $.each(chs, function () {
            s = s + "{name:'" + this + "',data:[]},";
        });
        s = s.substr(0, s.length - 1);
        s = s + "]";
        wchartInstance = new Highcharts.Chart({
            chart: {
                renderTo: 'chartArea',
                type: 'line'
            },
            credits: {
                enabled: false
            },
            exporting: {
                enabled: true
            },
            title: {
                text: '',
                x: -20 //center
            },
            xAxis: {
                type: 'datetime',
                labels: {
                    step: 4,
                    formatter: function () {
                        return new Date(this.value).toLocaleDateString();
                    }
                }
            },
            yAxis: {
                title: {
                    text: '数值'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function () {
                    if (this.series.name == '风向') {
                        var d = this.y;
                        var res = "";
                        if (d < 15 || d >= 345)
                            res = "北";
                        else if (d>= 15 && d<45)
                            res = "东北偏北";
                        else if (d >= 45 && d < 75)
                            res = "东北偏东";
                        else if (d >= 75 && d < 105)
                            res = "东";
                        else if (d >= 105 && d < 135)
                            res = "东南偏东";
                        else if (d >= 135 && d < 165)
                            res = "东南偏南";
                        else if (d >= 165 && d < 195)
                            res = "南";
                        else if (d >= 195 && d < 225)
                            res = "西南偏南";
                        else if (d >= 225 && d <255)
                            res = "西南偏西";
                        else if (d >= 255 && d < 285)
                            res = "西";
                        else if (d >= 285 && d < 315)
                            res = "西北偏西";
                        else if (d >=315 && d < 345)
                            res = "西北偏北";
                        return '<b>' + this.series.name + '：</b>' + res + '<br/> <b>时间：</b>' + new Date(this.x).toLocaleString();
                    }
                    else
                        return '<b>' + this.series.name + '：</b>' + this.y + '<br/> <b>时间：</b>' + new Date(this.x).toLocaleString();
                }

            },
            legend: {
                //layout: 'vertical',
                align: 'center',
                verticalAlign: 'top',
                borderWidth: 0
            },
            series: eval(s)
        });
    }
};